package com.zu.commu.landi2;

import com.zu.commu.context.ServerContext;
import com.zu.commu.interf.Action;
import com.zu.commu.interf.gprs.Engine;
import com.zu.commu.interf.gprs.Handle;
import com.zu.commu.interf.gprs.Response;
import com.zu.commu.interf.gprs.ResponseFactory;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.Iterator;

public class EngineImp implements Engine {
	private static ArrayList GPRSIDS;
	private static ResponseFactory responseFactory;
	private static EngineImp driver;
	private static sendHeartBeatThread shbt;

	public void setOnlyDriver() {
		if (driver == null)
			driver = this;
	}

	public boolean init(ArrayList GPRSIDS1, ResponseFactory responseFactory1) {
		GPRSIDS = GPRSIDS1;
		responseFactory = responseFactory1;
		shbt = new sendHeartBeatThread();
		shbt.start();
		return true;
	}

	public Handle getHandle() {
		return HandleFactoryImp.newInstance().createHandle();
	}

	public Response getResponse() {
		return responseFactory.createResponse();
	}

	public ArrayList getGPRSID() {
		return GPRSIDS;
	}

	private class sendHeartBeatThread extends Thread {
		private sendHeartBeatThread() {
		}

		public void run() {
			String sendHeartBeat = (String) ServerContext.GPRSProtocol_sendHeartBeat
					.get("landi2");
			if (sendHeartBeat.trim().equals("1")) {
				String heartBeatString = (String) ServerContext.GPRSProtocol_heartBeatString
						.get("landi2");
				String heartBeatTime = (String) ServerContext.GPRSProtocol_heartBeatTime
						.get("landi2");
				byte[] hbs = heartBeatString.getBytes();
				int hbtime = 5;
				try {
					hbtime = Integer.parseInt(heartBeatTime);
				} catch (Exception ee) {
					Logger log = Logger
							.getLogger("com.automic.commu.landi2.EngineImp");
					log.error("把心跳时间间隔转存整数出错，使用默认5分钟.");
					hbtime = 5;
				}
				long waitTime = hbtime * 60 * 1000L;
				boolean isException = false;
				String gprsId = null;
				Response rs = EngineImp.responseFactory.createResponse();
				while (true) {
					try {
						sleep(waitTime);
					} catch (Exception ee) {
						isException = true;
						Logger log = Logger
								.getLogger("com.automic.commu.landi2.EngineImp");
						log.error("间段发送心跳的线程睡眠发生异常 ！", ee);
					}
					if (isException) {
						isException = false;
						continue;
					}
					Iterator it = EngineImp.GPRSIDS.iterator();
					while (it.hasNext()) {
						gprsId = (String) it.next();
						rs.executeAction(gprsId, Action.SENDREMOTE, hbs);
					}
				}
			}
		}
	}
}
